package com.panda.mall.wares.category.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.panda.mall.common.base.BaseEnum;
import com.panda.mall.common.constants.ConfigConstants;
import com.panda.mall.common.mallElastic.feign.ElasticFeign;
import com.panda.mall.common.mallWares.dto.ExportCategoryDto;
import com.panda.mall.common.mallWares.dto.QueryCategoryDto;
import com.panda.mall.common.mallWares.entity.MallGoodsCategory;
import com.panda.mall.common.mallWares.enums.LevelEnum;
import com.panda.mall.wares.category.service.MallGoodsCategoryService;
import com.panda.mall.wares.category.mapper.MallGoodsCategoryMapper;
import lombok.SneakyThrows;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author tucy123
* @description 针对表【mall_goods_category(商品三级分类表)】的数据库操作Service实现
* @createDate 2022-12-23 10:04:55
*/
@Service
public class MallGoodsCategoryServiceImpl extends ServiceImpl<MallGoodsCategoryMapper, MallGoodsCategory> implements MallGoodsCategoryService{

    @Autowired
    MallGoodsCategoryMapper mallGoodsCategoryMapper;

    @Autowired
    ElasticFeign elasticFeign;

    /**
     * 新增或修改商品分类
     * @return
     */
    @Override
    public Boolean saveOrUpdateCategory(MallGoodsCategory mallGoodsCategory) {
        if (ObjectUtils.isEmpty(mallGoodsCategory.getId())){
            boolean save = this.saveOrUpdate(mallGoodsCategory);
            if (save){
                Long id = mallGoodsCategory.getId();
                String index = ConfigConstants.INDEX_category;
                elasticFeign.addDocument(id,index);
                return true;
            }
        }else {
            return this.saveOrUpdate(mallGoodsCategory);
        }
        return false;
    }

    /**
     * 删除商品分类
     * @param id
     * @return
     */
    @Override
    public Boolean deleteCategory(Long id) {
        int i = mallGoodsCategoryMapper.deleteById(id);
        return i != 0;
    }

    /**
     * 删除商品分类（完全）
     * @param id
     * @return
     */
    @Override
    public Boolean deletePhysicalCategory(Long id) {
        return mallGoodsCategoryMapper.deletePhysicalCategory(id);
    }

    /**
     * 批量删除商品分类
     * @param ids
     * @return
     */
    @Override
    public Boolean deleteAllCategory(List<Long> ids) {
        int i = mallGoodsCategoryMapper.deleteBatchIds(ids);
        return i != 0;
    }

    /**
     * 商品三级分类
     * @return
     */
    @Override
    public List<MallGoodsCategory> listCategoryTree() {
        //查询全部商品分类
        List<MallGoodsCategory> mallGoodsCategories = this.list();

        //筛选一级分类
        List<MallGoodsCategory> mallGoodsCategoryList = mallGoodsCategories.stream()
                .filter(mallGoodsCategory -> mallGoodsCategory.getParentId() == 0)
                .peek(mallGoodsCategory -> mallGoodsCategory.setChildren(getChild(mallGoodsCategory,mallGoodsCategories)))
                .sorted(Comparator.comparing(MallGoodsCategory::getSort))
                .collect(Collectors.toList());
        return mallGoodsCategoryList;
    }

    /**
     * 获取子菜单分类
     * @param mallGoodsCategory
     * @param mallGoodsCategories
     * @return
     */
    private List<MallGoodsCategory> getChild(MallGoodsCategory mallGoodsCategory, List<MallGoodsCategory> mallGoodsCategories) {
        List<MallGoodsCategory> categories = mallGoodsCategories.stream()
                .filter(goodsCategory -> goodsCategory.getParentId().equals(mallGoodsCategory.getId()))
                .peek(goodsCategory -> goodsCategory.setChildren(getChild(goodsCategory, mallGoodsCategories)))
                .sorted(Comparator.comparing(MallGoodsCategory::getSort))
                .collect(Collectors.toList());
        return categories;
    }

    /**
     * 查询三级商品
     * @return
     */
    @Override
    public List<MallGoodsCategory> queryCategory() {
        return this.lambdaQuery().eq(MallGoodsCategory::getCategoryLevel, LevelEnum.THERE.getValue()).list();
    }

    /**
     * 按id查询商品
     * @param id
     * @return
     */
    @Override
    public MallGoodsCategory queryCategoryById(Long id) {
        return this.baseMapper.selectById(id);
    }

    /**
     * 导出商品表
     * @param dto
     * @return
     */
    @Override
    @SneakyThrows
    public Boolean exportCategory(HttpServletResponse response, ExportCategoryDto dto) {
        List<MallGoodsCategory> data = this.lambdaQuery()
                .eq(ObjectUtil.isNotEmpty(dto.getCategoryName()),MallGoodsCategory::getCategoryName,dto.getCategoryName())
                .eq(ObjectUtil.isNotEmpty(dto.getParentId()),MallGoodsCategory::getParentId,dto.getParentId())
                .eq(ObjectUtil.isNotEmpty(dto.getCategoryLevel()),MallGoodsCategory::getCategoryLevel,dto.getCategoryLevel())
                .list();

        List<ExportCategoryDto> list = BeanUtil.copyToList(data, ExportCategoryDto.class);

        list.forEach(exportDto -> {
            MallGoodsCategory one = this.lambdaQuery().eq(MallGoodsCategory::getId, exportDto.getParentId()).one();
            if (ObjectUtil.isNotEmpty(one)){
                exportDto.setParentId(one.getCategoryName());
            }else {
                exportDto.setParentId("大宗商品");
            }
            exportDto.setCategoryLevel(LevelEnum.getByValue(Integer.valueOf(exportDto.getCategoryLevel())).getKey());
        });

        String fileName = "商品分类表:" + DateUtil.formatDate(new Date()) + ".xlsx";

        String resultFileName = URLEncoder.encode(fileName, "UTF-8");
        response.setCharacterEncoding("UTF-8");
        //response.setHeader("Content-Disposition", "attachment;filename=" + new String(resultFileName.getBytes(), StandardCharsets.ISO_8859_1));
        response.setHeader("Content-disposition", "attachment;filename=" + resultFileName);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        EasyExcel.write(response.getOutputStream(), ExportCategoryDto.class).sheet("导出数据").doWrite(list);

        return true;
    }

    /**
     * 分页查询商品分类
     * @return
     */
    @Override
    public Page<MallGoodsCategory> pageCategory(QueryCategoryDto dto) {
        Page<MallGoodsCategory> page = new Page<>(dto.getPageNum(),dto.getPageSize());
        QueryWrapper<MallGoodsCategory> wrapper = new QueryWrapper<>();
        wrapper.like("category_name",dto.getCategoryName());

        return null;
    }

}
